<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" :align-center="true">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="goodsForm"
        :rules="goodsRules"
        ref="goodsFormRef"
        label-position="top"
        class="demo-ruleForm"
        label-width="100px"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goodsForm.goods_cat"
                :options="categoriesList"
                :props="cateProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="iteam.attr_name"
              v-for="iteam in cateManyData"
              :key="iteam.attr_id"
            >
              <el-checkbox-group v-model="iteam.attr_vals">
                <el-checkbox :label="ite" v-for="(ite,i) in iteam.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="iteam.attr_name"
              v-for="iteam in cateOnlyData"
              :key="iteam.attr_id"
            >
              <el-input v-model="iteam.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-form-item>
              <el-upload
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture"
                :headers="headersObj"
                :on-success="handleSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <el-form-item>
              <quill-editor v-model="goodsForm.goods_introduce"></quill-editor>
              <el-button type="primary" class="addButton" @click="add">添加商品</el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <el-dialog title="图片信息" :visible.sync="dialogVisible" width="50%" @close="dialogClose">
        <img :src="previewUrl" />
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import _ from "lodash";
export default {
  data() {
    return {
      activeIndex: "0",
      goodsForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      goodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请输入商品种类", trigger: "blur" }
        ]
      },
      categoriesList: [],
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      cateManyData: [],
      cateOnlyData: [],
      headersObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      previewUrl: "",
      dialogVisible: false
    };
  },
  created() {
    this.getCategoriesList();
  },
  methods: {
    handlePreview(file) {
      this.previewUrl = file.response.data.url;
      this.dialogVisible = true;
    },
    dialogClose() {
      this.dialogVisible = false;
    },
    handleRemove(file) {
      const i = this.goodsForm.pics.findIndex(
        i => i.pic === file.response.data.tmp_path
      );
      this.goodsForm.pics.splice(i, 1);
    },
    handleSuccess(res) {
      const dataInfo = { pic: res.data.tmp_path };
      this.goodsForm.pics.push(dataInfo);
    },
    async getCategoriesList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) {
        return this.$message.error("获取分类列表失败");
      } else {
        this.categoriesList = res.data;
      }
    },
    handleChange() {
      if (this.goodsForm.goods_cat.length != 3) {
        this.goodsForm.goods_cat = [];
      }
    },
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName == 0 && this.goodsForm.goods_cat.length != 3) {
        this.$message.error("请输入商品分类");
        return false;
      }
    },
    async tabClick() {
      if (this.activeIndex == 1) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status != 200) return;
        this.cateManyData = res.data;
        this.cateManyData.forEach(iteam => {
          iteam.attr_vals = iteam.attr_vals ? iteam.attr_vals.split(" ") : [];
        });
      }
      if (this.activeIndex == 2) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (res.meta.status != 200) return;
        this.cateOnlyData = res.data;
      }
    },
    async add() {
      this.$refs.goodsFormRef.validate(async val => {
        if (!val) {
          this.$message.error("请填写必填项");
        }
        const form = _.cloneDeep(this.goodsForm);
        form.goods_cat = form.goods_cat.join(",");
        this.cateManyData.forEach(iteam => {
          const info = {
            attr_id: iteam.attr_id,
            attr_value: iteam.attr_vals.join(" ")
          };
          this.goodsForm.attrs.push(info);
        });
        this.cateOnlyData.forEach(iteam => {
          const info = { attr_id: iteam.attr_id, attr_value: iteam.attr_vals };
          this.goodsForm.attrs.push(info);
        });
        form.attrs = this.goodsForm.attrs;
        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status != 201) {
          this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        this.$router.push("/goods");
      });
    }
  },
  computed: {
    cateId() {
      if (this.goodsForm.goods_cat.length === 3) {
        return this.goodsForm.goods_cat[2];
      }
      return null;
    }
  }
};
</script>
<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.addButton {
  margin-top: 15px;
}
</style>